require('./Uploadimg.styl');
import PlusThin from 'salt-icon/lib/PlusThin';
import CrossRound from 'salt-icon/lib/CrossRound';
import { Boxs } from 'saltui'
const { HBox, Box, VBox } = Boxs;
import { Toast } from 'saltui';
const Girdview = require('components/girdview');
const readFileAsync = file => new Promise(resolve => {
    const reader = new FileReader()
    reader.onload = evt => resolve(evt.target.result)//读取到的文件编码成Data URL,base64,或者this.result
    reader.readAsDataURL(file)
})
class Uploadimg extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            src: '',
            urlList: props.urlList || []//所有显示的图片列表
        };
        this.handleClickBtn = this.handleClickBtn.bind(this);
        this.fileChoose = this.fileChoose.bind(this);
        this.handleClickDelBtn = this.handleClickDelBtn.bind(this);
        this.renderItem = this.renderItem.bind(this);
        this.iosFiles = [];//存储文件数据
        this.delEvaluateImgIds = [];//存储删除文件列表
    }
    //读取文件
    fileChoose() {
        let t = this;
        let src_arr = [];
        let files = this.imageInput.files;
        if (files.length + this.state.urlList.length > 9) {
            Toast.show({
                type: 'error',
                content: '图片数量超过上限'
            });
            return;
        }
        let formData = new FormData(this.refs.imageForm);
        if (this.formData) {
            for (let i = 0; i < files.length; i++) {
                this.formData.append("files", files[i])
            }
        } else {
            this.formData = formData;
        }
        if (navigator.userAgent.indexOf('iPhone') != -1) {
            for (let i = 0; i < files.length; i++) {
                t.iosFiles.push(files[i])
            }
        }
        for (let i = 0; i < files.length; i++) {
            // readFileAsync(files.item(i)).then((data) => {
            //     src_arr.push(data);
            //     if (files.length == src_arr.length) {
            //         t.setState({ urlList: this.state.urlList.concat(src_arr) });
            //     }
            // })
            let src = window.URL.createObjectURL(files[i]);
            src_arr.push({ src });
            t.setState({ urlList: t.state.urlList.concat(src_arr) });
        }
    }
    handleClickBtn() {
        // let imageInput = this.refs.imageInput.getDOMNode();
        this.imageInput.click();
    }
    handleClickDelBtn(index, evaluateImgId = undefined) {
        let t = this;
        let arr = this.state.urlList;
        arr.splice(index, 1);
        this.setState({ urlList: arr }, () => {
            if (evaluateImgId) {
                this.delEvaluateImgIds.push(evaluateImgId.toString());
                return;
            }
            if (navigator.userAgent.indexOf('Android') != -1) {
                if (t.formData) {
                    let formData = new FormData();
                    for (let i = 0; i < t.formData.getAll("files").length; i++) {
                        if (i != index) {
                            formData.append("files", t.formData.getAll("files")[i])
                        }
                    }
                    t.formData.delete("files");
                    t.formData = formData;
                }
            } else if (navigator.userAgent.indexOf('iPhone') != -1) {
                let formData = new FormData();
                let num = t.iosFiles.length;
                for (let i = 0; i < num; i++) {
                    if (index != i) {
                        formData.append("files", t.iosFiles[i])
                    }
                }
                t.iosFiles.splice(index, 1);
                t.formData = formData;
            }
        })
    }
    renderItem() {
        return (<HBox className="box">
            <form className="image-Form" ref="imageForm" >
                <input
                    className="image-Input"
                    type="file"
                    name="files"
                    multiple
                    accept="image/png,image/jpg,image/jpeg"
                    ref={(input) => { this.imageInput = input }}
                    onChange={this.fileChoose}
                />
            </form>
            <Box className="img-box">
                {this.state.src ?
                    <HBox>
                        <Box>
                            <CrossRound className="icon-cross-round" name="cross-round" width="20" height="20" fill="red" onClick={this.handleClickDelBtn} />
                            <p><img className="my-img" src={this.state.src} alt="" /></p>
                        </Box>
                    </HBox>
                    :
                    <div className="upload-img" >
                        <PlusThin width="75%" height="75%" fill="white" />
                    </div>
                }
            </Box>
        </HBox>)
    }
    render() {
        return (
            <div className="uploadimg">
                <div className="t-ML20 t-PT5 t-PB8">
                    图片
                {this.state.urlList.length > 0 && <span className="color t-ML8">{this.state.urlList.length}</span>}
                </div>
                <Girdview canDel girdItems={this.state.urlList} handleClickDelBtn={this.handleClickDelBtn}>
                    {this.state.urlList.length < 9 && this.renderItem()}
                </Girdview>
            </div>
        );
    }

    componentWillMount() {
    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
    }

    componentDidUpdate(prevProps, prevState) {
    }

    componentWillUnmount() {
    }
}

module.exports = Uploadimg;
